package com.xiaowen.util;


import com.xiaowen.service.TravelService;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by 15c on 2017/11/20.
 */
public class Myfilter implements Filter {
  private TravelService travelService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext sc = filterConfig.getServletContext();
        XmlWebApplicationContext cxt = (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(sc);

        if(cxt != null && cxt.getBean(TravelService.class) != null && travelService == null)
            travelService = (TravelService) cxt.getBean(TravelService.class);
    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        int travelId = Integer.parseInt(httpServletRequest.getParameter("travelId"));
        System.out.println("<<<<<<<<<<<<<<<<<<<travelId为：" + travelId);
        int i=0;
        try {
         i = travelService.addPageView(travelId);
            System.out.println("<<<<<<<<<<<<<<<<<<<i为：" + i);
        } catch (NullPointerException e) {
            System.out.println("NullPointerException");
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
